// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html


import ComponentBase from "../../general/Script/component/ComponentBase";
import { AssetsMgr, g_bundleName } from "../../general/Script/mgr/assetsManager";
import DataMgr from "../../general/Script/mgr/dataManager";
import GameMgr from "../../general/Script/mgr/gameManager";
import NativeMgr, { g_url_appid } from "../../general/Script/mgr/nativeManager";
import NetMgr, { g_rankType } from "../../general/Script/mgr/netManager";
import ServerMgr from "../../general/Script/mgr/serverManager";
import SoundMgr from "../../general/Script/mgr/soundManager";
import { subGameMgr } from "../../general/Script/mgr/SubGameMgr";
import RankingList from "../../general/Script/prefab/rankingList";
import { eHotUpdateEvent } from "../../general/Script/update/HotUpdateEvent";
import SubGameCtrl from "./Prefab/SubGameCtrl";



const { ccclass, property } = cc._decorator;

@ccclass
export default class Home extends ComponentBase {

    levelNode: cc.Node = null;
    userHead: cc.Node = null;
    userName: cc.Node = null;
    prize: cc.Node = null;

    showTest: number = 0;

    subGameContent: cc.Node = null;


    subGameScroll: cc.Node = null;


    testCount: number = 0;
    timesLabel: cc.Node = null;
    shareNode: cc.Node = null;
    async onLoad() {
        super.onLoad()
        this.initGameEvent();
        NativeMgr.Ins().getUserInfo(false);

        // NativeMgr.Ins().getCheckScene((active) => {
        //     this.prize.active = active;
        // });

        this.showTest = 0;

        // const adTestLayer = await AssetsMgr.obj().loadRes(g_bundleName.home, 'Prefab/adTestLayer') as cc.Prefab;

        // const leftPrize: cc.Node = cc.instantiate(adTestLayer);
        // GameMgr.Ins().addOnlyOneNode(this.node, leftPrize);

        if (DataMgr.Ins().subGameInfo) {
            this.initSubGame();
        } else {
            NetMgr.Ins().getSubGameConfig();
        }


        this.initUserData();

    }

    initGameEvent() {
        cc.systemEvent.on(eHotUpdateEvent.subGameGetConfigResult, this.initSubGame, this);


        cc.systemEvent.on('qrcode', (data) => {
            console.log('qrcode = ', data);
            cc.loader.load({ url: data, type: 'jpg' }, (err, spritFrame) => {
                if (err) {
                    console.log(err.message);
                }
                this.shareNode.active = true;
                const node = new cc.Node();
                const sp = node.addComponent(cc.Sprite);
                sp.spriteFrame = new cc.SpriteFrame(spritFrame);;
                node.parent = this.shareNode;
                node.x = 0;
                node.y = 0;

            })

        }, this);

        cc.systemEvent.on('toggleButtonCallBack', this.moduleChange.bind(this), this);

    }


    shareNodeCallBack() {
        this.shareNode.removeAllChildren(true);
        this.shareNode.active = false;
    }




    moduleChange(type) {
        console.log('moduleChange', type);
        const names = ['pkGame', 'normalGame'];
        if (names.indexOf(type) < 0) {
            return;
        }
        if (type == 'pkGame') {
            // subGameMgr.launchSubGame(g_bundleName.gameEat, 'gameEat');
        }

        this.subGameScroll.active = type == 'normalGame';
    }


    async initUserData() {
        const infoTotal = await NetMgr.Ins().servo.get(`/profile/fetch/${DataMgr.Ins().token}`);

        if (infoTotal.status == 200) {
            const data = infoTotal.body;

            console.log('initUserData data = ', data);
            DataMgr.Ins().userInfo.coin = data.coin;
            DataMgr.Ins().userInfo.redPack = Number(data.ecpm);
            DataMgr.Ins().userInfo.superior = data.superior || '';
            DataMgr.Ins().uid = data.uid;
            DataMgr.Ins().userInfo.rolling = data.rolling || 5;
            console.log('ecpm = 22 ', DataMgr.Ins().userInfo.redPack);

            this.bindUid()


        } else {
            GameMgr.Ins().showMsg('profile/fetch', infoTotal.body);
        }


    }

    async bindUid() {
        const uid = DataMgr.Ins().uid;

        const data = DataMgr.Ins().getLocalStorage('sceneData');
        if (data && data !== "" && DataMgr.Ins().userInfo.superior == "") {
            const dataStr = data.split(':');
            const keys = dataStr[0].split('_');
            const values = dataStr[1].split('_');
            const json: any = {}
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                if (key && key !== "") {
                    json[key] = values[i];
                }
            }

            // GameMgr.Ins().showMsg('绑定信息 = ' + uid + " to  " + JSON.stringify(json));

            const bindInfo = await NetMgr.Ins().servo.post(`/profile/bind/${DataMgr.Ins().token}`, { uid: json.uid }, true);
            if (bindInfo.status === 200) {
                const data = bindInfo.body;
                if (data.status === 'ok') {
                    GameMgr.Ins().showMsg('绑定成功' + json.uid);
                } else {
                    GameMgr.Ins().showMsg('绑定失败');
                }

            }

        }

    }
    initSubGame() {
        const datas = DataMgr.Ins().subGameInfo;
        this.subGameContent.removeAllChildren(true);

        datas.forEach(async (data) => {
            const subGamePrefab = await AssetsMgr.obj().loadRes(g_bundleName.home, 'Prefab/subGameItem') as cc.Prefab;
            let subGameNode = cc.instantiate(subGamePrefab);
            this.subGameContent.addChild(subGameNode);
            subGameNode.getComponent(SubGameCtrl).init(data);
        });
    }







    onDestroy(): void {
        console.error('homeManager onDestroy')
        super.onDestroy();
        cc.systemEvent.targetOff(this);
    }


    newGameCallBack() {
        console.log('newGameCallBack')
    }

    levelGameCallBack() {
        console.log('levelGameCallBack')
    }

    async shareGameCallBack() {
        console.log('shareGameCallBack')


        // const bundle = await AssetsMgr.obj().loadBundle(g_bundleName.gameBlock);
        // subGameMgr.launchSubGame(g_bundleName.gameBlock, 'gameBlock');
        // subGameMgr.launchSubGame(g_bundleName.gameSnake, 'gameSnake');


        const appid = NativeMgr.Ins().appId();

        NativeMgr.Ins().shareUrl(g_url_appid[appid], 'uid', DataMgr.Ins().uid);



    }


    async luckyCallBack() {
        // http://118.31.115.133:8086/games/rolling/meta 
        GameMgr.Ins().block()
        const infoTotal = await NetMgr.Ins().servo.get(`/games/rolling/meta`);
        GameMgr.Ins().unblock()
        if (infoTotal.status == 200) {
            const data = infoTotal.body;

            console.log('meta data = ', data);
            DataMgr.Ins().userInfo.rolling = 5 - data.count;
            DataMgr.Ins().rollingPool = data.pool;


            if (DataMgr.Ins().userInfo.rolling <= 0) {
                GameMgr.Ins().showMsg('今日次数已用完,明日再来!');
                return;
            }


            const prefab = await AssetsMgr.obj().loadRes(g_bundleName.resources, 'Prefab/lucky') as cc.Prefab;
            GameMgr.Ins().addOnlyOneNode(this.node, cc.instantiate(prefab));




        } else {
            GameMgr.Ins().showMsg('/games/rolling/rdm' + infoTotal.status);
            return;
        }


    }




    async rankCallBack() {

        const rank = await NetMgr.Ins().getRankList(g_rankType.coin);
        const prefab = await AssetsMgr.obj().loadRes(g_bundleName.resources, 'Prefab/rankingList') as cc.Prefab;
        const node = GameMgr.Ins().addOnlyOneNode(this.node, cc.instantiate(prefab));
        node.getComponent(RankingList).init(rank.data, rank.user);

    }

    async prizeCallBack() {
        console.log('prizeCallBack')
        // this.testCount++;
        // this.timesLabel.getComponent(cc.Label).string = 'prizeCallBack' + this.testCount.toString();

        const prefab = await AssetsMgr.obj().loadRes(g_bundleName.resources, 'Prefab/redPackage') as cc.Prefab;
        GameMgr.Ins().addOnlyOneNode(this.node, cc.instantiate(prefab));

    }

    async userHeadCallBack() {
        console.log('userHeadCallBack')

        const prefab = await AssetsMgr.obj().loadRes(g_bundleName.home, 'Prefab/userInfo') as cc.Prefab;
        GameMgr.Ins().addOnlyOneNode(this.node, cc.instantiate(prefab));
    }






}
